﻿package com.sz.common.query.servlet;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.sz.common.CommonDAO;
import com.sz.common.ICommonDAO;

import java.lang.reflect.Method;


public class QueryServlet extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	protected final Log logger = LogFactory.getLog(getClass());
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
//		PrintWriter out = response.getWriter();
//		out.println("错误的调用");
		//response.sendRedirect("index.jsp?username=aaa&message=kao");
		
		
		
	}
	
	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {			
			String[] bm = request.getParameter("BEAN_METHOD").split("\\.");
			String bean = bm[0];
			String method = bm[1];
			
			String methodCount = request.getParameter("METHOD_COUNT");
			
			String paramClass = request.getParameter("PARAM_CLASS");
			
			String paramValue = request.getParameter("PARAM_VALUE");
			Map map = (Map)JSONSerializer.toJSON(paramValue);
			
			//分页的参数
			String methodPage = request.getParameter("METHOD_PAGE");
			String begin = request.getParameter("PAGE_BEGIN");
			String end = request.getParameter("PAGE_END");
			
			ServletContext servletContext = request.getSession().getServletContext();        
			ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
			ICommonDAO dao = (ICommonDAO)context.getBean("CommonDAO");
			Object obj = context.getBean(bean);
			
			//参数的类
			Class[] ac = new Class[1];
			ac[0] = Class.forName(paramClass);
			
			//得到方法
			Class gc = obj.getClass();
			Method m = gc.getMethod(method, ac);
			Method mc = null;
			if(methodCount != null && !methodCount.equals("")) {
				mc = gc.getMethod(methodCount, ac); 
			}
			Method mp = null; //分页的method
			if(methodPage != null && !methodPage.equals("")) {
				mp = gc.getMethod(methodPage, ac);
			}
			
			//在bean上调用方法
			/*注意相应的sqlmap配置中，parameterClass="java.util.Map" 
			 *若写成parameterClass="java.util.HashMap"会导致类型转换失败
			 *因为上面JSONSerializer.toJSON的返回不是HashMap，仅实现了Map接口而已
			 */			
			
			//count
			Long count = null;
			if(mc != null) {
				logger.info(String.format("调用方法: %s.%s", bean, methodCount));
				count = (Long)mc.invoke(obj, map);				
			}
			
			List list = null;
			if(mp != null) { //分页
				logger.info(String.format("调用方法: %s.%s", bean, methodPage));
				map.put("__BEGIN", begin);
				map.put("__END", end);
				list = (List)mp.invoke(obj, map); 
			} else {
				logger.info(String.format("调用方法: %s.%s", bean, method));
				list = (List)m.invoke(obj, map); 
			}
			
			StringBuffer buf = new StringBuffer();
			buf.append("{");
			if(count != null) {
				buf.append(String.format("COUNT:%s,", count.toString()));
			}
			buf.append("LIST:[");
			for(int n = 0; n < list.size(); ++n) {				
				JSONObject temp = JSONObject.fromObject(list.get(n));
				buf.append(temp.toString());
				if(n < list.size()-1) buf.append(",");
			}			
			buf.append("]");
			buf.append("}");

			response.setCharacterEncoding("utf-8");
			response.getWriter().print(buf.toString());
		} catch (Exception e) {
			logger.error(e.getMessage());
			throw new ServletException(e.getMessage());
		}

	}
}

